package com.migu.contacts.main;

import static com.migu.contacts.net.Service.API;

import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;

import androidx.fragment.app.Fragment;

import com.frank.libandroid.AttachPopup;
import com.frank.libandroid.BaseAdapter;
import com.frank.libandroid.BaseFragment;
import com.frank.libandroid.DataStore;
import com.frank.libandroid.HttpCallback;
import com.frank.libandroid.butterknife.BindAdapter;
import com.frank.libandroid.butterknife.OnClick;
import com.frank.libandroid.util.RadioGroupUtil;
import com.lxj.xpopup.XPopup;
import com.migu.contacts.R;
import com.migu.contacts.bean.ContactBean;
import com.migu.contacts.bean.GroupBean;
import com.migu.contacts.bean.IndustryBean;
import com.migu.contacts.databinding.FragmentHomeBinding;
import com.migu.contacts.databinding.ItemHomeBinding;
import com.migu.contacts.databinding.PopDefaultBinding;
import com.migu.contacts.databinding.PopFilterBinding;
import com.migu.contacts.util.CheckBoxUtil;
import com.migu.contacts.util.GroupUtil;
import com.migu.contacts.util.IndustryUtil;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseFragment<FragmentHomeBinding> {
    @BindAdapter(R.id.recyclerView)
    BaseAdapter<ItemHomeBinding, ContactBean> adapter = new BaseAdapter<ItemHomeBinding, ContactBean>() {
        @OnClick(R.id.root)
        public void goDetail(ItemHomeBinding binding, ContactBean bean) {
            DataStore.put(ContactEditActivity.CONTACT_BEAN_KEY, bean);
            start(ContactEditActivity.class);
        }

        @Override
        protected void onBindData(ItemHomeBinding binding, ContactBean bean, int position) {
            super.onBindData(binding, bean, position);
            if (position > 0 && mList.get(position - 1).firstLetter.equals(bean.firstLetter)) {
                binding.firstLetter.setVisibility(View.GONE);
            } else {
                binding.firstLetter.setVisibility(View.VISIBLE);
            }
            if (position == mList.size() - 1) {
                binding.space.setVisibility(View.VISIBLE);
            } else {
                binding.space.setVisibility(View.GONE);
            }
        }

        @OnClick(R.id.delete)
        public void delete(ItemHomeBinding binding, ContactBean bean) {
            Log.d(TAG, "delete() called with: binding = [" + binding + "], bean = [" + bean + "]");
            API.contactsDelete(bean.id).watch(mActivity, new HttpCallback<Boolean>() {
                @Override
                protected void onSuccess(Boolean aBoolean) {
                    mList.remove(bean);
                    adapter.notifyDataSetChanged();
                }
            });
        }
    };

    @Override
    protected void initView() {
        super.initView();
    }

    @Override
    protected void initData() {
        super.initData();
        API.queryGroup().watch(this, new HttpCallback<List<GroupBean>>() {
            @Override
            protected void onSuccess(List<GroupBean> groupBeans) {
                GroupUtil.setGroups(groupBeans);
            }
        });
        API.getIndustry().watch(this, new HttpCallback<List<IndustryBean>>() {
            @Override
            protected void onSuccess(List<IndustryBean> industryBeans) {
                IndustryUtil.setData(industryBeans);
            }
        });
    }

    List<ContactBean> allList = new ArrayList<>();
    List<ContactBean> currentList = new ArrayList<>();

    @Override
    public void onResume() {
        super.onResume();
        API.contactsAll().watch(this, new HttpCallback<List<ContactBean>>() {
            @Override
            protected void onSuccess(List<ContactBean> contactBeans) {
                for (ContactBean contactBean : contactBeans) {
                    contactBean.firstLetter = contactBean.namePinyin.substring(0, 1).toUpperCase();
                }
                allList.clear();
                allList.addAll(contactBeans);
                currentList.clear();
                currentList.addAll(allList);
                sortList();
                Log.d(TAG, "onSuccess() called with: contactBeans = [" + contactBeans + "]");
            }
        });
    }

    @OnClick(R.id.search)
    public void search() {
        start(SearchActivity.class);
    }

    @OnClick(R.id.notice)
    public void notice() {
        start(NoticeActivity.class);
    }

    int sortType = 0;

    @OnClick(R.id.defaultFilter)
    public void showDefault() {
        AttachPopup<PopDefaultBinding> attachPopup = new AttachPopup<PopDefaultBinding>(getContext()) {
            @Override
            protected void initView() {
                super.initView();
                RadioGroupUtil.checkIndex(mBinding.radio, sortType);
                mBinding.radio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        Log.d(TAG, "onCheckedChanged() called with: group = [" + group + "], checkedId = [" + checkedId + "]");
                        sortType = RadioGroupUtil.getCheckedIndex(group);
                        sortList();
                        dismiss();
                    }
                });
            }
        };
        new XPopup.Builder(getContext()).atView(mBinding.defaultFilter).asCustom(attachPopup).show();
    }

    private void sortList() {
        String filterText = "";
        switch (sortType) {
            case 0: {
                filterText = "默认";
                currentList.sort(new Comparator<ContactBean>() {
                    @Override
                    public int compare(ContactBean o1, ContactBean o2) {
                        return o1.firstLetter.compareTo(o2.firstLetter);
                    }
                });
                break;
            }
            case 1: {
                filterText = "时间";
                currentList.sort(new Comparator<ContactBean>() {
                    @Override
                    public int compare(ContactBean o1, ContactBean o2) {
                        return o2.createTime.compareTo(o1.createTime);
                    }
                });
                break;
            }
            case 2: {
                filterText = "重要";
                currentList.sort(new Comparator<ContactBean>() {
                    @Override
                    public int compare(ContactBean o1, ContactBean o2) {
                        return o2.importance - o1.importance;
                    }
                });
                break;
            }
        }
        adapter.setData(currentList);
        mBinding.filter1.setText(filterText);
    }

    public static class FilterBean {
        public int industryIndex = -1;
        public int eduIndex = -1;
        public int importanceIndex = -1;
        public int groupIndex = -1;

        public int getIndustryId() {
            return IndustryUtil.getId(getIndustryName());
        }

        public String getIndustryName() {
            switch (industryIndex) {
                case 0:
                    return "电子商务";
                case 1:
                    return "计算机软件";
                case 2:
                    return "移动互联网";
            }
            return "";
        }

        public int getGroupId() {
            return GroupUtil.getGroupId(getGroupName());
        }

        public String getGroupName() {
            switch (groupIndex) {
                case 0:
                    return "亲人";
                case 1:
                    return "朋友";
                case 2:
                    return "客户";
            }
            return "";
        }

        @Override
        public String toString() {
            return "FilterBean{" +
                    "industryIndex=" + industryIndex +
                    ", eduIndex=" + eduIndex +
                    ", importanceIndex=" + importanceIndex +
                    ", groupIndex=" + groupIndex +
                    '}';
        }
    }

    FilterBean filterBean = new FilterBean();

    @OnClick(R.id.filterFilter)
    public void showFilter() {
        AttachPopup<PopFilterBinding> attachPopup = new AttachPopup<PopFilterBinding>(getContext()) {
            @Override
            protected void initView() {
                super.initView();
                CheckBoxUtil.checkOne(mBinding.radio1);
                CheckBoxUtil.checkOne(mBinding.radioXueli);
                CheckBoxUtil.checkOne(mBinding.radio3);
                CheckBoxUtil.checkOne(mBinding.radioGuanXi);
                Log.d(TAG, "initView() called" + filterBean);
                CheckBoxUtil.checkIndex(mBinding.radio1, filterBean.industryIndex);
                CheckBoxUtil.checkIndex(mBinding.radioXueli, filterBean.eduIndex);
                CheckBoxUtil.checkIndex(mBinding.radio3, filterBean.importanceIndex);
                CheckBoxUtil.checkIndex(mBinding.radioGuanXi, filterBean.groupIndex);
            }

            @OnClick(R.id.quit)
            public void quit() {
                dismiss();
            }

            @OnClick(R.id.low)
            public void low() {
                CheckBoxUtil.checkIndex(mBinding.radio3, 0);
            }

            @OnClick(R.id.mid)
            public void mid() {
                CheckBoxUtil.checkIndex(mBinding.radio3, 1);
            }

            @OnClick(R.id.high)
            public void high() {
                CheckBoxUtil.checkIndex(mBinding.radio3, 2);
            }

            @OnClick(R.id.confirm)
            public void confirm() {
                filterBean.industryIndex = CheckBoxUtil.getCheckedIndex(mBinding.radio1);
                filterBean.eduIndex = CheckBoxUtil.getCheckedIndex(mBinding.radioXueli);
                filterBean.importanceIndex = CheckBoxUtil.getCheckedIndex(mBinding.radio3);
                filterBean.groupIndex = CheckBoxUtil.getCheckedIndex(mBinding.radioGuanXi);
                Log.d(TAG, "confirm() called" + filterBean);
                filterList();
                dismiss();
            }
        };
        new XPopup.Builder(getContext()).atView(mBinding.defaultFilter).asCustom(attachPopup).show();
    }

    private void filterList() {
        List<ContactBean> collect = allList.stream().filter(new Predicate<ContactBean>() {
            @Override
            public boolean test(ContactBean bean) {
                if (filterBean.getIndustryId() != -1) {
                    if (bean.jobList == null || bean.jobList.isEmpty()) {
                        return false;
                    }
                    boolean b = bean.jobList.stream().anyMatch(new Predicate<ContactBean.JobList>() {
                        @Override
                        public boolean test(ContactBean.JobList jobList) {
                            if (jobList.industryId == filterBean.getIndustryId()) {
                                return true;
                            }
                            return false;
                        }
                    });
                    if (!b) {
                        return false;
                    }
                }
                if (filterBean.eduIndex != -1 && bean.edu != filterBean.eduIndex + 1) {
                    return false;
                }
                if (filterBean.importanceIndex != -1 && (bean.importance != filterBean.importanceIndex + 1)) {
                    return false;
                }
                if (filterBean.getGroupId() != -1) {
                    boolean b = bean.groupIdList.stream().anyMatch(new Predicate<Integer>() {
                        @Override
                        public boolean test(Integer integer) {
                            return (integer == filterBean.getGroupId());
                        }
                    });
                    if (!b) {
                        return false;
                    }
                }
                return true;
            }
        }).collect(Collectors.toList());
        currentList.clear();
        currentList.addAll(collect);
        adapter.setData(currentList);
    }
}